Skip to content

Backup block, VM creation, nesting allowed, --force panic fixed - #7

Merged
unidoc-ahall merged 2 commits into
masterfrom
feat/backup-block-nesting-vm-create
Oct 11, 2026
Merged

unidoc-ahall merged 2 commits into
masterfrom
feat/backup-block-nesting-vm-create

Conversation

@unidoc-ahall

Copy link
Copy Markdown
Contributor

Closes #4, closes #5, closes #6.

What

Test plan

  • go build ./... && go vet ./... && go test ./...: clean locally, CI confirms
  • Real host: a plan shows the backup update, apply sets the key, a second plan is all match
  • Real host: a type: virtual-machine instance with an image is created and reaches Running
  • After merge: just release 0.2.0 (version.txt is already 0.2.0 in this PR)

…e --force panic

backup: block (incus-backup selection)
- backup: {policy: nightly} sets the Incus key user.backup.policy, backup: {exclude: true}
  sets user.backup.exclude and removes the policy key. These are the keys incus-backup
  reads (an explicit key on the instance wins over the backup server's assignments).
- Only those two keys are touched, and only when the block is declared: a key set by
  hand survives an absent block. An empty block removes both keys.
- New instances get the keys at create; existing ones through the plan entry
  <instance>.backup (the update patches single keys with the etag).
- policy and exclude are mutually exclusive; a policy name is letters, digits, - _ . (max 63).

Allow security.nesting (#4)
- security.nesting=true is no longer reported as a policy violation: nesting inside an
  unprivileged container is allowed. security.privileged=true and
  security.idmap.isolated=false stay banned.

Fix the panic with --force (#5)
- A policy-violation plan entry has no executor; Plan.Apply called it anyway, so
  `sync --apply --force` panicked on a nil function. Such entries are now reported
  as left as is: sync never rewrites the forbidden keys.

Create virtual machines (#6)
- New instance field type: container (default) | virtual-machine, used on create.
  The create request carries the type, the wait is 600 s for a VM, and import/adopt
  keep type: virtual-machine for an adopted VM.
- provision:, and before.sh / after.sh / files/ next to instance.yaml, are refused for a
  VM (they run inside the guest and need the Incus agent); provisioning is also skipped
  for a VM at create as a second guard.

README and docs/schema.md describe all of it. version.txt is 0.2.0.
unidoc-alip
unidoc-alip previously approved these changes Oct 11, 2026

@unidoc-alip unidoc-alip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: APPROVE — 0 must-fix; 5 should-fix and 2 nit, proposed as follow-up work in a separate PR

This PR adds a backup: block that writes the incus-backup selection keys (user.backup.policy / user.backup.exclude), removes security.nesting from the isolation ban (#4), stops sync --apply --force from calling a nil executor on a policy-violation entry (#5), and lets the fleet create virtual machines with type: virtual-machine (#6). Build, vet, tests and gofmt pass in CI and locally at d015a52.

The main changes work. Removing nesting from the ban is correct (an unprivileged container with nesting is what #4 asks for, and security.privileged=true / security.idmap.isolated=false are still refused). The --force panic is gone: a PoC panics on master and does not panic on this branch. The VM create request carries the type. The findings are edge cases in the new backup: block (keys inherited from a profile; how an "empty" block is spelled), a VM validation that rejects the directory incus-sync create scaffolds, the #5 fix being keyed on the wrong condition, and the plan not showing what a create will make. None blocks the merge: each needs an uncommon setup (F1, F2), has a workaround (F3), or is a hardening or plan-output gap (F4, F5). Approving so the #5 panic fix ships, with the findings grouped into follow-ups below.

Each finding was checked with a PoC that runs three variants side by side: base (master), head (this PR) and fixed (the suggested change). All existing tests and go vet / gofmt still pass on fixed. The PoC tests and the end-to-end script are in full in the Appendix at the end, with the command to run each. Findings are keyed F1, F2, ... rather than with a hash and a number, which GitHub would autolink to issues and PRs.

Suggested follow-ups (one PR, or one issue each):

  • Backup block correctness: F1 (profile-provided user.backup.exclude) and F2 (spellings of an empty block; reject unknown keys). Add a docs note that backup: {} cannot remove a policy that comes from a profile.
  • VM ergonomics and docs: F3 (empty scaffolded files/) and F5 (type and backup keys in the create details). Add the two missing docs items: docs/schema.md stating the nesting/privileged policy (#4), and that existing VMs can be declared the same way (#6 comment).
  • #5 hardening: F4 (an explicit policy-report marker; an error for a missing executor) plus the remaining regression tests (each forbidden key, with and without --force).
  • F6 and F7 can ride along with any of these.

F1 [should-fix] internal/incus/plan.go line 1120 — the backup plan diffs local Config, but incus-backup reads ExpandedConfig

planInstanceBackup compares and unsets keys in existing.Config, which holds only the instance's own keys. incus-backup selects from ExpandedConfig (profile keys included): Resolve in internal/client/engine/discover.go on unidoc/incus-backup#1 reads o.Instance.ExpandedConfig. Its precedence is exclude first, then an explicit user.backup.policy. Its design doc (section 6) presents profile inheritance as intended ("inherited through profiles (so a profile can opt a whole class in)").

The case that matters: a profile sets user.backup.exclude=true, and the instance file declares backup: {policy: nightly}. Sync sets the local policy key. It "unsets" exclude only if it is a local key, and here it is not. The plan then reports match forever, but incus-backup still sees exclude=true and skips the instance. The fleet says the instance is backed up nightly; it is not, and nothing reports it.

PoC (TestPoC7F1BackupBlockAgainstProfileKeys) runs the real planInstanceBackup and the real updateInstanceConfig closure against a fake server that computes ExpandedConfig as the profile keys overlaid by the local keys. It then applies incus-backup's selection rule, copied from Resolve / isTrue:

head   profile sets exclude, fleet declares a policy:   plan1=update|backup=excluded|plan2=match
head   same, policy already set locally:                plan1=match|backup=excluded|plan2=match
fixed  profile sets exclude, fleet declares a policy:   plan1=update|backup=selected:nightly|plan2=match
fixed  same, policy already set locally:                plan1=update|backup=selected:nightly|plan2=match

The two control cases (no profile keys; exclude declared over a local policy) behave the same on head and fixed.

Caveat: the fake server models the Incus rule that a local key overrides the same key from a profile in ExpandedConfig. That rule was not exercised against a real Incus here. unidoc/incus-backup#1 is not merged yet.

Suggested fix: compare against the effective config. When a policy is declared and exclude is effectively on, override it locally with "false", because an instance key cannot remove a profile key.

	eff := existing.ExpandedConfig
	if eff == nil {
		eff = existing.Config
	}
	want := map[string]string{}
	for k, v := range set {
		want[k] = v
	}
	var deltas []string
	var toUnset []string
	for _, k := range unset {
		_, local := existing.Config[k]
		switch {
		case k == model.BackupExcludeKey && desired.Backup.Policy != "":
			// exclude beats policy in incus-backup: it must not be in effect. An
			// instance key cannot remove a profile's key, but "false" overrides it.
			if backupTrue(eff[k]) {
				want[k] = "false"
			}
		case local:
			toUnset = append(toUnset, k)
			deltas = append(deltas, fmt.Sprintf("%s: %q → (unset)", k, existing.Config[k]))
		}
	}
	for _, k := range sortedKeys(want) {
		if got, ok := eff[k]; !ok || got != want[k] {
			deltas = append(deltas, fmt.Sprintf("%s: %q → %q", k, eff[k], want[k]))
		}
	}
	set = want

// backupTrue mirrors incus-backup's reading of user.backup.exclude.
func backupTrue(s string) bool {
	switch strings.ToLower(s) {
	case "true", "1", "yes", "on":
		return true
	}
	return false
}

One behaviour change: a hand-set local exclude=true on an instance that now declares a policy becomes exclude=false instead of being removed. Removing it could expose a profile value underneath, so "false" is the safer choice.

A related limit worth documenting: backup: {} cannot remove a user.backup.policy that comes from a profile.


F2 [should-fix] docs/schema.md line 224 / internal/model/instance.go line 350 — what counts as an "empty backup: block"

The docs say: "An empty backup: block (no policy, no exclude) removes both keys." That holds only for some spellings. The loader is a plain yaml.Unmarshal (loader.go line 660). A null value leaves the *InstanceBackup pointer nil, and a nil pointer means "absent".

PoC (TestPoC7F2EmptyBackupBlockSpellings, real readYAMLFile + BackupConfig, head):

flow mapping {}:             managed=true|set=map[]|unset=[user.backup.policy user.backup.exclude]
bare key:                    managed=false|set=map[]|unset=[]
policy line commented out:   managed=false|set=map[]|unset=[]
misspelt key:                managed=true|set=map[]|unset=[user.backup.policy user.backup.exclude]

That leaves two problems:

  • Commenting out the line keeps the key. The schema example shows backup: with policy: under it. Commenting out the policy: line, the obvious way to stop backing an instance up, leaves a bare backup:. That is treated as absent, so the key stays and the instance keeps being backed up. That contradicts line 224.
  • A typo removes the selection. A misspelt key (polcy: nightly) is silently ignored and leaves an empty block, which removes both keys. The plan does show (unset), but the instance drops out of backups because of a typo.

Suggested fix:

  • Say backup: {} explicitly in the docs.
  • Reject unknown keys inside the block, following the existing Address.UnmarshalYAML idiom in addressset.go. The fixed variant turns the typo into a load error. The other three rows are unchanged.
// UnmarshalYAML refuses unknown keys: the fleet loader is not strict, and a
// misspelt key (polcy:) would otherwise leave an empty block, which removes
// both keys from the instance.
func (b *InstanceBackup) UnmarshalYAML(node *yaml.Node) error {
	if node.Kind == yaml.MappingNode {
		for i := 0; i+1 < len(node.Content); i += 2 {
			if k := node.Content[i].Value; k != "policy" && k != "exclude" {
				return fmt.Errorf("line %d: unknown key %q in backup: (policy or exclude)", node.Content[i].Line, k)
			}
		}
	}
	type raw InstanceBackup
	return node.Decode((*raw)(b))
}
# `backup: {}` removes both keys. A bare `backup:` with nothing under it is YAML
# null and counts as an absent block: the keys are left alone.

F3 [should-fix] internal/config/validate.go line 336 — the empty files/ that incus-sync create scaffolds makes a VM fail validation

incus-sync create always creates an empty files/ next to instance.yaml (cmd/incus-sync/cmd_create.go line 52). The VM check refuses any files entry that exists, so the documented way to start a new instance fails once type: virtual-machine is added.

End-to-end PoC with the real binary: copy examples/minimal-fleet, run incus-sync create vm1 --host web1, append project: default and type: virtual-machine, then run incus-sync validate --host web1:

head   files/ entries: 0
       Error: instance "vm1": files next to instance.yaml is not supported for virtual machines (...)
fixed  files/ entries: 0
       (validates)

An empty files/ pushes nothing. Also, createInstance already skips provisioning for a VM as a second guard. Treat an empty files/ as absent. This also moves the SourceDir == "" check out of the loop, where it currently sits as a break:

			// the instance directory is applied at create time too: before.sh, files/ and after.sh.
			// An empty files/ (as `incus-sync create` scaffolds it) pushes nothing and is fine.
			if inst.SourceDir != "" {
				for _, f := range []string{"before.sh", "after.sh", "files"} {
					p := filepath.Join(inst.SourceDir, f)
					if _, err := os.Stat(p); err != nil {
						continue
					}
					if f == "files" {
						if entries, err := os.ReadDir(p); err == nil && len(entries) == 0 {
							continue
						}
					}
					return fmt.Errorf("instance %q: %s next to instance.yaml is not supported for virtual machines (it runs inside the guest, which needs the Incus agent there)", name, f)
				}
			}

TestVMRefusesProvisioningFilesInItsDirectory (instance_type_test.go line 43) currently asserts that an empty files/ is refused, so it needs a file inside files/. With that change it passes on the fixed variant. TestPoC7F3ScaffoldedDirectoryForAVM checks both sides: empty-files=ok|populated-files=refused.

The fix treats any entry as "populated", so a .gitkeep (the usual way to commit an empty directory) would be refused again; skipping dotfiles is your call. A --type flag on create (which could skip files/ for a VM) would be a nice addition, but it is not needed for the fix.


F4 [should-fix] internal/incus/plan.go line 226 — the #5 fix is keyed on "no executor", and the report still reads as an update

The panic is fixed. The PoC (TestPoC7F4PolicyReportIsNotAnUpdate, real planInstances + Plan.Apply) panics on master for both remaining forbidden keys, and does not panic on head. But the guard is e.execUpdate == nil, not "this entry is a policy report". Two consequences:

  • A forgotten executor would be hidden. Any future ActionUpdate entry that forgets its executor would be printed as "policy violation, reset it by hand", and Apply would report success. Today only the policy entries lack one: every other ActionUpdate in plan.go sets execUpdate. Issue #5 asked for exactly this case: "Apply must never call a nil execUpdate for any action (defensive check that returns an error naming the entry)".
  • Dry-run and apply disagree. The dryRun branch comes before the guard, so the dry-run plan, including the == PLAN == block that sync --apply prints just before applying, still shows ~ update instance c1. Only the apply step says "left as is". (Summary() also counts the report as an update; the fix below leaves that alone so the action values stay stable.)
base   dry=~ update instance c1|err=<nil> || apply=|err=PANIC
head   dry=~ update instance c1|err=<nil> || apply=! left as is instance c1 (policy violation, reset it by hand)|err=<nil>
fixed  dry=! policy violation instance c1 (left as is, reset it by hand)|err=<nil> || apply=! policy violation instance c1 (left as is, reset it by hand)|err=<nil>

forgotten executor (TestPoC7F4ForgottenExecutorIsAnError):
base   |err=PANIC
head   ! left as is instance-device web.eth0 (policy violation, reset it by hand)|err=<nil>
fixed  |err=update instance-device "web.eth0" in project "": plan entry has no executor (bug)

Suggested fix: mark the report explicitly, handle it before the dryRun branch, and make a missing executor an error. Keeping ActionUpdate leaves diff --json (schema v1, action field) and both renderers in cmd_diff.go unchanged. A new ActionPolicy, the option #5 preferred, would also work, but then renderPlan, renderPlanSummary and renderPlanJSON have to handle it, or the entry disappears from diff.

	execCreate func(incusclient.InstanceServer) error
	execUpdate func(incusclient.InstanceServer) error
	// policyReport marks a fleet-policy violation: shown and gated like an
	// update, never executed (sync does not rewrite the forbidden keys).
	policyReport bool
}

// in Apply, before `switch e.Action`:
		if e.policyReport {
			// --force got past the refusal; the instance is left as it is.
			fmt.Printf("  ! policy violation %s %s (left as is, reset it by hand)\n", e.Kind, label)
			for _, d := range e.Details {
				fmt.Printf("      %s\n", d)
			}
			continue
		}

// ActionUpdate (and the same for execCreate in ActionCreate):
			if e.execUpdate == nil {
				return fmt.Errorf("update %s %q in project %q: plan entry has no executor (bug)", e.Kind, e.Name, e.Project)
			}

// in the planInstances policy loop:
					policyReport: true,

(execCreate has no nil guard either. Every ActionCreate entry sets one today, so that case is unreachable; the fix covers it for symmetry.)

#5 also asked for regression tests on each forbidden key, with and without --force. The PR tests security.privileged through Apply only. The PoC covers security.idmap.isolated too. The refusal without --force lives in cmd_sync.go, which has no tests.


F5 [should-fix] internal/incus/plan.go line 656 — the plan never shows the type or backup keys of a create

The diff output is the review step for this tool. A create entry's details are original_image, profiles, devices (and templates). They do not say whether the new instance is a virtual machine or which user.backup.* keys it gets. Both are now part of the create request.

PoC (TestPoC7F5CreateDetailsShowTypeAndBackup, real planInstances):

head   details: original_image: images:debian/13; profiles: [default]; devices: []
fixed  details: original_image: images:debian/13; profiles: [default]; devices: []; type: virtual-machine; user.backup.policy: nightly
			if desired.IsVM() {
				details = append(details, "type: virtual-machine")
			}
			if set, _, managed := desired.BackupConfig(); managed {
				for _, k := range sortedKeys(set) {
					details = append(details, fmt.Sprintf("%s: %s", k, set[k]))
				}
			}

Related, and source-read only: type: that disagrees with an existing instance (for example, the fleet says virtual-machine but the live instance is a container) produces no signal at all. That is documented ("Only used on create"), so a warning detail would be enough if you want one.


F6 [nit] internal/incus/plan.go line 746 — createInstance's doc comment now sits on instanceCreateRequest

instanceCreateRequest was inserted between createInstance's comment and the function. godoc for instanceCreateRequest now starts with "createInstance builds an api.InstancesPost and creates the container.", and createInstance has no comment. Move lines 746-748 down to createInstance.


F7 [nit] small consistency items

  • The backup details use -> (plan.go lines 1121, 1128). Every other plan detail uses → (fieldDiffAddressSet, diffDeviceKeys).
  • The --force help text (cmd/incus-sync/cmd_sync.go line 162) still lists only "empty ACL/set, widening ingress-default". Since --force is now the documented way past a policy violation (README), it could mention that too.

PR description verification

  • "Closes #4": confirmed. security.nesting is out of forbiddenInstanceConfig; TestIsolationPolicyAllowsNestingAndBansPrivileged covers all three keys through planInstances, as #4 asks. One gap: #4's acceptance list asks for README and docs/schema.md to state the policy. README does (line 311). docs/schema.md does not mention nesting or privileged.
  • "Closes #5": partially confirmed. The panic is gone (PoC: base panics, head does not). The issue's own fix spec (a dedicated action, or a defensive error naming the entry) and its test list (each key, with and without --force) are not met. See F4.
  • "Closes #6": partially confirmed. The create request carries the type (TestCreateRequestTypeFollowsTheDeclaredType). The wait is 600 s for a VM. provision: is refused, and provisioning is skipped at create. Adopt and import write type: virtual-machine (InstanceFromAPI). Two notes:
    • The author's comment on #6 (2026-10-07) narrowed it to "future, not planned now", so this PR goes beyond what the issue last said, which is fine but worth noting when closing it.
    • The comment's docs item, "docs/schema.md should say that existing virtual machines can be declared the same way", is not done. Line 211 says only that type is used on create.
  • "backup: ... Only those two keys are touched, only when the block is declared": confirmed. planInstanceBackup returns early without a block, and updateInstanceConfig changes only the listed keys. Mechanically it is GetInstance → modify → UpdateInstance(inst.Writable(), etag), a full PUT guarded by the etag (the same pattern as updateInstanceDevice and incus config set), not a PATCH. Commit message: "patches single keys with the etag" is accurate in effect. See F1 for keys that come from a profile, and F2 for which YAML spellings count as "declared".
  • "An explicit key on the instance wins over the backup server's own assignments" (README, schema.md): confirmed against incus-backup source. Resolve in internal/client/engine/discover.go ranks exclude, then an explicit key, then server assignment. That code is on unidoc/incus-backup#1 (open, review/initial-import); the incus-backup default branch has only .gitignore.
  • "a policy name is letters, digits, - _ . (max 63)": confirmed in ValidBackupPolicyName. This is incus-sync's own rule; I found no policy-name validator in unidoc/incus-backup#1 to match it against.
  • "go build ./... && go vet ./... && go test ./...: clean locally, CI confirms": confirmed. The CI test job passed on d015a52 and also runs gofmt. Reproduced locally (build, vet, test, gofmt -l empty).
  • "Real host: a plan shows the backup update ..." and "Real host: a type: virtual-machine instance ... reaches Running": not verified. Both boxes are unchecked in the description, and there is no evidence either ran against a real Incus. The F1 and F2 PoCs model Incus; they do not replace these checks.
  • "version.txt is already 0.2.0": confirmed.

Appendix: PoC files

Drop the three test files into the paths named in their headings, then run them. They assert the behaviour the findings propose, so on this PR's head they fail by design; with the suggested fixes applied they pass. poc7_policy_test.go also compiles on master, where it shows the original panic.

go test ./internal/incus ./internal/config -run TestPoC7 -v -count=1

Expected outcomes (head / fixed) are quoted in each finding above.

internal/incus/poc7_policy_test.go (F4)

package incus

// PoC for PR #7 review, finding F4 (policy-violation report vs. Plan.Apply).
// Exercises the real planInstances + Plan.Apply from internal/incus/plan.go
// (head d015a52). Compiles on master too, so base/head/fixed run the same file:
//
//	go test ./internal/incus -run TestPoC7F4 -v
//
// Caveat: Apply is called with a nil server. Every entry here either has no
// project (so UseProject is never called) or must not reach an executor.

import (
	"fmt"
	"io"
	"os"
	"strings"
	"testing"

	"github.com/lxc/incus/v7/shared/api"

	"github.com/unidoc/incus-sync/internal/config"
)

func poc7Live(name string, cfg map[string]string) api.Instance {
	return api.Instance{Name: name, InstancePut: api.InstancePut{Config: cfg}}
}

// poc7Apply runs Apply and returns "<first output line>|err=<err or panic>".
func poc7Apply(p *Plan, dryRun bool) (outcome string) {
	r, w, _ := os.Pipe()
	stdout := os.Stdout
	os.Stdout = w
	var errStr string
	func() {
		defer func() {
			if rec := recover(); rec != nil {
				errStr = "PANIC"
			}
		}()
		if err := p.Apply(nil, dryRun); err != nil {
			errStr = err.Error()
		} else {
			errStr = "<nil>"
		}
	}()
	w.Close()
	os.Stdout = stdout
	out, _ := io.ReadAll(r)
	first := strings.TrimSpace(strings.SplitN(string(out), "\n", 2)[0])
	return fmt.Sprintf("%s|err=%s", first, errStr)
}

// Each forbidden key (issue #5 acceptance list): the report must never panic, and dry-run and
// apply should both say what happens (the instance is left as is), not "~ update".
func TestPoC7F4PolicyReportIsNotAnUpdate(t *testing.T) {
	for _, kv := range [][2]string{{"security.privileged", "true"}, {"security.idmap.isolated", "false"}} {
		p := &Plan{}
		planInstances(p, &config.Fleet{}, []api.Instance{poc7Live("c1", map[string]string{kv[0]: kv[1]})})
		got := "dry=" + poc7Apply(p, true) + " || apply=" + poc7Apply(p, false)
		want := "dry=! policy violation instance c1 (left as is, reset it by hand)|err=<nil> || apply=! policy violation instance c1 (left as is, reset it by hand)|err=<nil>"
		t.Logf("%s: %s", kv[0], got)
		if got != want {
			t.Errorf("%s:\n got  %s\n want %s", kv[0], got, want)
		}
	}
}

// An ordinary update entry whose executor was forgotten (a future plan.go bug) must fail loudly,
// not be printed as a "policy violation" while apply reports success.
func TestPoC7F4ForgottenExecutorIsAnError(t *testing.T) {
	p := &Plan{Entries: []PlanEntry{{
		Kind: "instance-device", Name: "web.eth0", Action: ActionUpdate,
		Details: []string{`security.acls: "a" → "a,b"`},
	}}}
	got := poc7Apply(p, false)
	t.Logf("%s", got)
	if !strings.Contains(got, "err=update instance-device \"web.eth0\"") {
		t.Errorf("got %s, want an error naming the entry", got)
	}
}

internal/incus/poc7_backup_test.go (F1, F5)

package incus

// PoC for PR #7 review, findings F1 (profile-provided user.backup.exclude) and
// F5 (create details). Runs the real planInstanceBackup, updateInstanceConfig
// and planInstances from internal/incus/plan.go (head d015a52) against a fake
// server that keeps ExpandedConfig = profile config overlaid by local config.
//
//	go test ./internal/incus -run 'TestPoC7F1|TestPoC7F5' -v
//
// poc7BackupSelects is transplanted from incus-backup
// internal/client/engine/discover.go (branch review/initial-import, Resolve
// and isTrue): exclude in ExpandedConfig wins, then user.backup.policy in
// ExpandedConfig. Server assignments and default_policy are not modelled
// (they rank below an explicit key, so they cannot change these outcomes).

import (
	"context"
	"fmt"
	"strings"
	"testing"

	incusclient "github.com/lxc/incus/v7/client"
	"github.com/lxc/incus/v7/shared/api"

	"github.com/unidoc/incus-sync/internal/config"
	"github.com/unidoc/incus-sync/internal/model"
)

type poc7Op struct{ incusclient.Operation }

func (poc7Op) WaitContext(context.Context) error { return nil }

// poc7Srv implements only GetInstance and UpdateInstance; anything else panics.
type poc7Srv struct {
	incusclient.InstanceServer
	profile map[string]string
	local   map[string]string
}

func (s *poc7Srv) instance() api.Instance {
	exp := map[string]string{}
	for k, v := range s.profile {
		exp[k] = v
	}
	loc := map[string]string{}
	for k, v := range s.local {
		exp[k] = v
		loc[k] = v
	}
	return api.Instance{Name: "web", InstancePut: api.InstancePut{Config: loc}, ExpandedConfig: exp}
}

func (s *poc7Srv) GetInstance(string) (*api.Instance, string, error) {
	i := s.instance()
	return &i, "etag", nil
}

func (s *poc7Srv) UpdateInstance(_ string, put api.InstancePut, _ string) (incusclient.Operation, error) {
	s.local = put.Config
	return poc7Op{}, nil
}

func poc7BackupSelects(exp map[string]string) string {
	switch strings.ToLower(exp[model.BackupExcludeKey]) {
	case "true", "1", "yes", "on":
		return "excluded"
	}
	if p := exp[model.BackupPolicyKey]; p != "" {
		return "selected:" + p
	}
	return "no-policy"
}

// plan -> apply -> what incus-backup selects -> plan again.
func poc7Cycle(t *testing.T, desired model.Instance, srv *poc7Srv) string {
	var steps []string
	for round := 1; round <= 2; round++ {
		p := &Plan{}
		planInstanceBackup(p, "web", desired, srv.instance())
		if len(p.Entries) != 1 {
			t.Fatalf("round %d: %d entries", round, len(p.Entries))
		}
		e := p.Entries[0]
		steps = append(steps, fmt.Sprintf("plan%d=%s", round, e.Action))
		if round == 1 {
			if e.Action == ActionUpdate {
				if err := e.execUpdate(srv); err != nil {
					t.Fatal(err)
				}
			}
			steps = append(steps, "backup="+poc7BackupSelects(srv.instance().ExpandedConfig))
		}
	}
	return strings.Join(steps, "|")
}

func TestPoC7F1BackupBlockAgainstProfileKeys(t *testing.T) {
	policy := model.Instance{Name: "web", Backup: &model.InstanceBackup{Policy: "nightly"}}
	exclude := model.Instance{Name: "web", Backup: &model.InstanceBackup{Exclude: true}}
	for _, tc := range []struct {
		name    string
		desired model.Instance
		profile map[string]string
		local   map[string]string
		want    string
	}{
		{"control: no profile keys", policy, nil, nil,
			"plan1=update|backup=selected:nightly|plan2=match"},
		{"control: exclude wins over a local policy", exclude, nil, map[string]string{model.BackupPolicyKey: "nightly"},
			"plan1=update|backup=excluded|plan2=match"},
		{"profile sets exclude, fleet declares a policy", policy, map[string]string{model.BackupExcludeKey: "true"}, nil,
			"plan1=update|backup=selected:nightly|plan2=match"},
		{"same, policy already set locally", policy, map[string]string{model.BackupExcludeKey: "true"}, map[string]string{model.BackupPolicyKey: "nightly"},
			"plan1=update|backup=selected:nightly|plan2=match"},
	} {
		got := poc7Cycle(t, tc.desired, &poc7Srv{profile: tc.profile, local: tc.local})
		t.Logf("%-48s %s", tc.name+":", got)
		if got != tc.want {
			t.Errorf("%s:\n got  %s\n want %s", tc.name, got, tc.want)
		}
	}
}

// A create entry is what a reviewer reads in `diff`; it should say it creates a VM, and which
// backup keys the new instance gets.
func TestPoC7F5CreateDetailsShowTypeAndBackup(t *testing.T) {
	desired := model.Instance{Name: "vm1", Type: model.InstanceTypeVM, OriginalImage: "images:debian/13",
		Backup: &model.InstanceBackup{Policy: "nightly"}}
	p := &Plan{}
	planInstances(p, &config.Fleet{Instances: map[string]model.Instance{"vm1": desired}}, nil)
	if len(p.Entries) != 1 || p.Entries[0].Action != ActionCreate {
		t.Fatalf("%+v", p.Entries)
	}
	d := strings.Join(p.Entries[0].Details, "; ")
	got := fmt.Sprintf("type-shown=%v|backup-shown=%v", strings.Contains(d, "virtual-machine"), strings.Contains(d, model.BackupPolicyKey))
	t.Logf("details: %s", d)
	if got != "type-shown=true|backup-shown=true" {
		t.Errorf("got %s", got)
	}
}

internal/config/poc7_test.go (F2, F3)

package config

// PoC for PR #7 review, findings F2 (spellings of an "empty" backup: block) and
// F3 (VM validation vs. the directory `incus-sync create` scaffolds).
// Uses the real readYAMLFile (loader.go), model.Instance.BackupConfig and
// Fleet.validateInstances (validate.go) at head d015a52.
//
//	go test ./internal/config -run TestPoC7 -v

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/unidoc/incus-sync/internal/model"
)

func poc7Decode(t *testing.T, body string) string {
	path := filepath.Join(t.TempDir(), "instance.yaml")
	if err := os.WriteFile(path, []byte("instance: web\nproject: default\n"+body), 0o644); err != nil {
		t.Fatal(err)
	}
	var inst model.Instance
	if err := readYAMLFile(path, &inst); err != nil {
		return "decode-error"
	}
	set, unset, managed := inst.BackupConfig()
	return fmt.Sprintf("managed=%v|set=%v|unset=%v", managed, set, unset)
}

// docs/schema.md line 224 (head): "An empty `backup:` block (no policy, no exclude) removes both keys."
func TestPoC7F2EmptyBackupBlockSpellings(t *testing.T) {
	for _, tc := range []struct{ name, body, want string }{
		{"flow mapping {}", "backup: {}\n",
			"managed=true|set=map[]|unset=[user.backup.policy user.backup.exclude]"},
		// YAML null: the pointer stays nil, so this is "absent" (keys kept), whatever the docs say.
		{"bare key", "backup:\n",
			"managed=false|set=map[]|unset=[]"},
		{"policy line commented out", "backup:\n  # policy: nightly\n",
			"managed=false|set=map[]|unset=[]"},
		// A misspelt key must not silently turn into "remove both keys".
		{"misspelt key", "backup:\n  polcy: nightly\n",
			"decode-error"},
	} {
		got := poc7Decode(t, tc.body)
		t.Logf("%-28s %s", tc.name+":", got)
		if got != tc.want {
			t.Errorf("%s:\n got  %s\n want %s", tc.name, got, tc.want)
		}
	}
}

// cmd/incus-sync/cmd_create.go:52 always creates an empty files/ next to instance.yaml.
func TestPoC7F3ScaffoldedDirectoryForAVM(t *testing.T) {
	validate := func(dir string) string {
		f := &Fleet{Instances: map[string]model.Instance{"web": {Name: "web", Type: model.InstanceTypeVM, SourceDir: dir}}}
		if err := f.validateInstances(); err != nil {
			return "refused"
		}
		return "ok"
	}
	scaffold := t.TempDir()
	if err := os.MkdirAll(filepath.Join(scaffold, "files"), 0o755); err != nil {
		t.Fatal(err)
	}
	populated := t.TempDir()
	if err := os.MkdirAll(filepath.Join(populated, "files", "etc"), 0o755); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(populated, "files", "etc", "motd"), []byte("hi\n"), 0o644); err != nil {
		t.Fatal(err)
	}
	got := strings.Join([]string{"empty-files=" + validate(scaffold), "populated-files=" + validate(populated)}, "|")
	t.Logf("%s", got)
	if want := "empty-files=ok|populated-files=refused"; got != want {
		t.Errorf("got  %s\nwant %s", got, want)
	}
}

poc7_f3_e2e.sh (F3, end to end with the real binary)

Usage: go build -o /tmp/incus-sync ./cmd/incus-sync && ./poc7_f3_e2e.sh /tmp/incus-sync /tmp/poc7-e2e "$PWD". The second argument must be a scratch directory: the script deletes and recreates it.

#!/bin/bash
# PoC F3 end-to-end: incus-sync create (real scaffold) + type: virtual-machine -> validate
set -u
BIN=$1; WORK=$2; REPO=$3
rm -rf "$WORK"; mkdir -p "$WORK"; cp -R "$REPO/examples/minimal-fleet" "$WORK/fleet"
cd "$WORK/fleet"
"$BIN" --fleet-path . create vm1 --host web1 --image images:debian/13 --description "test vm" >/dev/null
printf 'project: default\ntype: virtual-machine\n' >> hosts/web1/instances/vm1/instance.yaml
ls -A hosts/web1/instances/vm1/files | wc -l | xargs echo "files/ entries:"
"$BIN" --fleet-path . validate --host web1 2>&1 | tail -2

…policy reports

- F1: the backup plan compares against the effective config (ExpandedConfig), which is what
  incus-backup reads. A profile that sets user.backup.exclude=true while the instance
  declares a policy gets user.backup.exclude=false on the instance (an instance key cannot
  remove a profile key); the plan reports an update until it is set.
- F2: an unknown key inside backup: (polcy:) is a load error instead of an empty block that
  removes both keys. Docs: backup: {} removes both keys, a bare backup: is absent, and an
  empty block cannot remove a policy that comes from a profile.
- F3: a VM accepts an empty files/ (what `incus-sync create` scaffolds) and a files/ that
  holds only dotfiles; before.sh, after.sh and a populated files/ are still refused.
- F4: a policy-violation entry is marked (policyReport), handled before the dry-run branch
  and printed the same in dry run and apply ("! policy violation ... left as is"). A plan
  entry without an executor is now an error naming the entry, for update and create.
- F5: the create details show type: virtual-machine and the user.backup.* keys.
- F6: createInstance's doc comment is back on createInstance.
- F7: plan details use the arrow of the other details; the --force help names policy
  violations.
- Docs: docs/schema.md states the isolation policy (nesting allowed, privileged and a
  shared idmap refused, what --force does) and that an existing VM is declared the same way.

The reviewer's PoC tests are in as regression tests (policy_report_test.go,
backup_profile_test.go, backup_strict_test.go).

@unidoc-alip unidoc-alip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: APPROVE: 0 must-fix, 0 should-fix. F1-F7 from the review of d015a52 are all resolved; 2 nits and 2 known gaps remain, none blocking

Re-review of 860e242 ("Address the PR review: effective backup config, strict backup block, policy reports"). The author put the follow-ups in this PR instead of a separate one. Every finding is fixed as proposed. Docs items are covered too: docs/schema.md now states the isolation policy (#4), and it says an existing VM is declared the same way (#6).

How this was checked:

  • Build, vet, go test -race ./... and gofmt -l all pass locally at 860e242. The CI test job also passes on 860e242.
  • The original appendix PoCs were run unmodified (only the test names were changed, to avoid clashing with the ported copies) in a worktree at 860e242. They were written to fail on d015a52 and pass on the fix, and all six now pass. The F3 end-to-end script with the real binary also passes: validate exits 0 on a scaffolded VM directory.
  • The ported regression tests (policy_report_test.go, backup_profile_test.go, backup_strict_test.go) keep every row of the PoCs. None was weakened. TestVMRefusesProvisioningFilesInItsDirectory now uses a populated files/. TestVMAllowsAnEmptyFilesDirectory is new and covers both an empty files/ and one holding only .gitkeep.

F1 [resolved] the backup plan compares against the effective config

planInstanceBackup now diffs against ExpandedConfig, with Config as a fallback. When a policy is declared and exclude is in effect, it writes exclude=false. The original PoC passes all four rows. The two profile cases now give backup=selected:nightly. The live instances come from GetInstances(api.InstanceTypeAny) (plan.go:152). The client sets recursion=1, so it returns full instance objects with expanded_config. The fallback to Config should therefore not trigger against a real server. That last step is inferred from the Incus API; it was not run against a real Incus.

F2 [resolved] strict backup: block and docs

InstanceBackup.UnmarshalYAML refuses keys other than policy and exclude. The loader is gopkg.in/yaml.v3 (loader.go:32, :660), so the hook fires, and the PoC's misspelt-key row is now decode-error. The {}, bare-key and commented-line rows are unchanged. docs/schema.md explains backup: {}, the bare backup:, the effective-config rule, and that a policy set by a profile cannot be removed.

F3 [resolved] a VM accepts the scaffolded files/

An empty files/, or one holding only dotfiles, passes validation. before.sh, after.sh and a populated files/ are still refused. Both the PoC and the e2e script pass.

F4 [resolved] explicit policy-report marker and a missing-executor error

policyReport is handled before the dry-run branch. Both sync and the == PLAN == block that sync --apply prints go through plan.Apply(srv, true) (cmd_sync.go:99, :122), so dry run and apply now print the same ! policy violation ... left as is line. A nil execUpdate or execCreate is now an error naming the entry. Safety check: every other ActionUpdate and ActionCreate entry in plan.go sets its executor (lines 286, 296, 402, 412, 682, 746, 1172). Apply switches only on Create and Update. PlanEntry is built only inside internal/incus. So the new error cannot fire on a valid plan.

F5 [resolved] create details show type: virtual-machine and the user.backup.* keys (PoC output confirms)

F6 [resolved] createInstance's doc comment is back on createInstance

F7 [resolved] no -> is left in plan.go, and the --force help names policy violations


N1 [nit] internal/config/validate.go: hasVisibleEntries skips a dot-directory that has content

files/.cfg/a passes VM validation (checked: validate exits 0). The container push path (provision.go, filepath.WalkDir) does not skip dotfiles, so a container would get /.cfg/a, while a VM silently gets nothing. The impact is low because createInstance never provisions a VM (plan.go:857). Possible fix: ignore only dot files at the top level, not dot directories.

N2 [nit, by design] diff still renders the policy report as ~ update

renderPlan, renderPlanSummary and renderPlanJSON key on Action, and Summary() counts the report as an update. The original review proposed keeping it this way so that diff --json (schema v1) stays stable. Noted only so it is not mistaken for a regression.

Known gaps (unchanged, not blocking)

  • #5 asked for a regression test of the refusal without --force. That logic is in cmd_sync.go, and cmd/incus-sync still has no tests.
  • The two real-host checkboxes in the PR description are still unchecked. Nothing here replaces them: the F1 and F4 tests use fake servers or a nil server.

@unidoc-ahall
unidoc-ahall merged commit 1d6ab71 into master Oct 11, 2026
1 check passed
@unidoc-ahall
unidoc-ahall deleted the feat/backup-block-nesting-vm-create branch October 11, 2026 14:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants